<!-- 发布 -->
<template>
	<view>
		<loadPage :loading="dataLoad"></loadPage>
		<template v-show="!dataLoad">
			<view class="itemone">
				<u-form class="itemwidth" :model="form" ref="goodsForm"
					:label-style="{'font-size':'24rpx','color':'rgba(56, 56, 56, 1)','height':'40rpx'}">
					<u-form-item>
						<addressSelect :addressId="addressId"></addressSelect>
					</u-form-item>
					<u-form-item label="种类" class="uform" label-width='100' prop="type">
						<u-input placeholder="请输入种类" v-model="form.type" type="string" height="30"
							placeholder-style="color:rgba(166, 166, 166, 1);font-size:20rpx" />
					</u-form-item>
					<u-form-item label="品类" label-width='100' class="uform" prop="varieties">
						<u-input placeholder="请输入品类" v-model="form.varieties" type="string" height="30"
							placeholder-style="color:rgba(166, 166, 166, 1);font-size:20rpx" />
					</u-form-item>
					
					<u-form-item label="重量(kg)" class="uform" label-width='150' prop="kilogram">
						<u-input placeholder="请输入重量" v-model="form.kilogram" type="number" height="30"
							placeholder-style="color:rgba(166, 166, 166, 1);font-size:20rpx" />
					</u-form-item>
					<u-form-item label="单价(元/kg)" class="uform" label-width='180' prop="price">
						<u-input placeholder="请输入单价" v-model="form.price" type="number" height="30"
							placeholder-style="color:rgba(166, 166, 166, 1);font-size:20rpx" />
					</u-form-item>
					<u-form-item label="备注" label-width='100' label-position="left" prop="remarks">
						<u-input placeholder="其他说明" v-model="form.remarks" type="string" auto-height
							placeholder-style="color:rgba(166, 166, 166, 1);font-size:20rpx" />
					</u-form-item>
					<u-form-item label="是否预售" class="uform" label-width="200">
						<u-switch activeColor="rgba(255, 87, 51, 1)" v-model="switchVal" size="40">
						</u-switch>
					</u-form-item>
					<u-form-item label="交货日期" label-width="200" class="uform" v-if="switchVal">
						<view class="date_input" @click="showDateSelect = true">
							<u-datetime-picker :show="showDateSelect" v-model="time" ref="datetimePicker" :formatter="formatter"
								mode="datetime" @confirm="timeSelect" @cancel="cancel()">
							</u-datetime-picker>
							<u-input placeholder="请选择日期" v-model="form.goodsNewTime" type="text"
								placeholder-style="color:rgba(166, 166, 166, 1);font-size:20rpx" disabled />
						</view>
					</u-form-item>
					<u-form-item label="商品图片" class="uform" label-width="200">
						<u-upload @afterRead="afterRead" @delete="deletePic" name="1" :multiple="true" :maxCount="6"
							:fileList="tempImageList" :previewFullImage="true" width="180" height="180" uploadText='请放入图片'>
						</u-upload>
					</u-form-item>
				</u-form>
			</view>
			<Agreement v-model="checked" name="产品发布免责声明" :type="agreementType.disclaimer"/>
			<button class="send_button" @click="submit">{{buttontext}}</button>
			<view class="screenheight"></view>
		</template>
	</view>
</template>

<script>
	import addressSelect from 'components/address/addressSelect'
	import Agreement from "components/agreement/index"
	import loadPage from "components/common/loadPage"
	import goodsRules from 'utils/verify/goodsRules';
	import {agreementType} from "utils/enums/agreement"
	import guid from "utils/guid.js"
	import {
		uploadProductImg
	} from 'apis/file';
	import {
		getGoodsInfo,
		releasePreSellProduct,
		releaseOnSellProduct,
		processingReleaseOnSellProduct,
		modifyProductInfo
	} from 'apis/farmer/goods.js';
	import {
		mapGetters
	} from "vuex"
	const dateTypeOption = {
		year: '年',
		month: '月',
		day: '日'
	}
	export default {
		components: {
			addressSelect,
			loadPage,
			Agreement
		},
		data() {
			return {
				agreementType,
				checked: [],
				showDateSelect: false, //显示时间选择器
				dataLoad: false, //是否需要加载数据
				time: Number(new Date()),
				switchVal: false, //预售
				// sec: false, //状态
				tempImageList: [], // 临时图片路径，用于预览图
				fileList1: [], //图片列表
				form: {
					varieties: '', // 品名
					type: '', // 种类
					kilogram: '', //重量
					price: '', //单价
					remarks: '', // 备注
					status: 0, // 商品状态
					goodsNewTime: '', //预售时间
					// imgList: []
				},
				goodsRules,
				pageState: 0, //页面状态 0表示发布新商品的状态，1表示修改商品的状态
				sendType: 0, // 商品类型，0 初级（默认），1 加工
				addressId: null, // 地址id
				// rules: goodsRules
			}
		},
		computed: {
			...mapGetters({
				getUserAddressById: "getUserAddressById",
				getDefaultAddress: "getDefaultAddress"
			}),
			buttontext(){
				return this.pageState === 0 ? "发布" : "保存"
			}
		},
		watch: {
			"$store.state.addressStore.defaultId"(newVal){
				this.addressId = newVal
			}
		},
		methods: {
			asyncChange(i) {
				this.switchVal = i
				this.form.goodsNewTime = ''
			},
			//时间选择器
			timeSelect(e) {
				this.showDateSelect = false;
				const timeFormat = uni.$u.timeFormat
				this.form.goodsNewTime = timeFormat(e.value, 'yyyy-mm-dd hh:MM')
			},
			cancel() {
				this.showDateSelect = false;
			},
			/* 时间格式化 */
			formatter(type, value) {
				const newType = dateTypeOption[type]
				return newType ? value + newType : value
			},
			// 删除图片
			deletePic(event) {
				this.tempImageList.splice(event.index, 1)
			},
			// 图片上传
			async afterRead(event) {
				const that = this
				const lists = event.file
				lists.forEach(item => {
					const uuid = guid()
					that.tempImageList.push({
						url: item.url,
						uuid,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < that.tempImageList.length; i++) {
					const {
						status,
						url,
						uuid
					} = that.tempImageList[i]
					if (status === "success") continue;
					const result = await uploadProductImg(url)
					const {
						code,
						data,
					} = JSON.parse(result)
					that.tempImageList.forEach(item => {
						if (item.uuid === uuid) {
							Object.assign(item, {
								status: code === 200 ? 'success' : 'error',
								message: code === 200 ? "上传成功" : "上传失败",
								url: code === 200 ? data[0] : item.url
							})
						}
					})
				}
			},
			// 提交表单
			submit() {
				const that = this
				if (!that.checked.length) return that.$errorMsg('请阅读并勾选免责声明')
				if (that.switchVal && that.form.goodsNewTime == '') return that.$errorMsg("预售时间不能为空");
				if (that.tempImageList.length === 0) return that.$errorMsg("至少上传一张图片");
				let productionArea = "贵州省长顺县";
				let marketTime = that.switchVal ? that.form.goodsNewTime + ':00' : "";
				let data = {
					'contactInfoId': that.addressId ? that.addressId : that.getDefaultAddress['id'], //发布人信息
					'productVariety': that.form.varieties, //品名
					'productSpecies': that.form.type, //种类
					'productRemark': that.form.remarks, //备注
					'productPrice': that.form.price, //单价
					'productWeight': that.form.kilogram, //重量
					'productProductionArea': productionArea, //生产地区
					'productStatus': +that.switchVal, //状态
					'marketTime': marketTime, //上架时间
					// 从临时地址中读取图片列表
					'productImgList': that.tempImageList.filter(item => item.status === "success").map(item => item.url)
				}
				that.$refs.goodsForm.validate().then(async () => {
					let func = that.switchVal ? releasePreSellProduct : releaseOnSellProduct
					if(Number(that.sendType) === 1){
						/*  如果是加工产品，则调用对应的接口  */
						func = that.switchVal ? processingReleaseOnSellProduct : processingReleaseOnSellProduct
					}
					if(that.pageState){
						func = modifyProductInfo
						Object.assign(data,{
							id: that.form['id'],
							type: that.goodsType
						})
					}
					const {
						code,
						msg
					} = await func(data)
					if (code !== 200) return that.$errorMsg(msg);
					that.$successMsg(`${that.pageState?"修改":"发布"}成功`)
					setTimeout(that.goback, 1000)
				})
			},
			async loadData(id){
				this.dataLoad = true
				/* 根据路由携带的id加载数据 */
				const that = this
				const {code,msg,data} = await getGoodsInfo(id,0)
				if(code !== 200) return that.$showTitleModule(msg, that.goback)
				that.addressId = data['contactInfoId']
				Object.assign(that.form,{
					id: data['id'],
					varieties: data['productVariety'],
					type:  data['productSpecies'],
					remarks:  data['productRemark'],
					price:  data['productPrice'] + '',
					kilogram:  data['productWeight'] + '',
					goodsNewTime: data['marketTime'],
					
				})
				that.switchVal = !!data['productStatus']
				data['imgList'].forEach(item => {
					const uuid = guid()
					that.tempImageList.push({
						status: 'success',
						message: "上传成功",
						url: item,
						uuid
					})
				})
				this.dataLoad = false
			}
		},
		async onLoad(){
			
			/* 如果路由参数中携带了id，说明是需要编辑商品信息 */
			const {id,goodsType,pageType,sendType} = this.$Route.query
			if(id){
				uni.setNavigationBarTitle({
					title: "编辑商品"
				})
				this.pageState = 1
				this.pageType = pageType
				this.goodsType = goodsType
				await this.loadData(id)
			}
			/*  修改页面发布的商品级别  */
			if(sendType){
				uni.setNavigationBarTitle({
					title: "发布加工产品"
				})
				this.sendType = sendType?sendType:this.sendType
			}
			
			
		},
		
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			if (this.switchVal) {
				this.$refs.datetimePicker.setFormatter(this.formatter)
			};
			this.$refs.goodsForm.setRules(this.goodsRules);
		}
	}
</script>
<style>
	@import url("sends_goods.css");
</style>
